package com.sl.hx.shop.ui.home.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.DynamicDrawableSpan;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.page.AlibcBasePage;
import com.alibaba.baichuan.android.trade.page.AlibcDetailPage;
import com.alibaba.baichuan.android.trade.page.AlibcPage;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sl.hx.shop.R;
import com.sl.hx.shop.base.BaseActivity;
import com.sl.hx.shop.bean.CheckCollect;
import com.sl.hx.shop.bean.ProductDetail;
import com.sl.hx.shop.bean.RelationBean;
import com.sl.hx.shop.bean.ShopDetail;
import com.sl.hx.shop.ui.home.adapter.RelationListAdapter;
import com.sl.hx.shop.ui.home.contacts.GoodsDetailContacts;
import com.sl.hx.shop.ui.home.presenter.GoodsDetailPresenter;
import com.sl.hx.shop.ui.mine.activity.LoginActivity;
import com.sl.hx.shop.utils.ConfigUtil;
import com.sl.hx.shop.utils.ScreenUtil;
import com.sl.hx.shop.utils.ToastUtil;
import com.sl.hx.shop.utils.UMShareUtil;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;

/**
 * 商品详情页
 */

public class GoodsDetailActivity extends BaseActivity<GoodsDetailContacts.view, GoodsDetailPresenter> implements GoodsDetailContacts.view {

    @BindView(R.id.detail_banner)
    BGABanner mBanner;
    @BindView(R.id.goodsName)
    TextView mGoodsName;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.zk_final_price)
    TextView zkFinalPrice;
    @BindView(R.id.reserve_price)
    TextView reservePrice;
    @BindView(R.id.volume)
    TextView volume;
    @BindView(R.id.shop_icon)
    ImageView shopIcon;
    @BindView(R.id.shop_title)
    TextView shopTitle;
    @BindView(R.id.seller_nick)
    TextView sellerNick;
    @BindView(R.id.detail_scrollview)
    NestedScrollView detailScrollview;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.collect)
    ImageView collect;
    @BindView(R.id.price_buy)
    TextView priceBuy;
    @BindView(R.id.price_coupon)
    TextView priceCoupon;
    @BindView(R.id.coupon_info)
    TextView couponinfo;
    @BindView(R.id.ll_coupon)
    LinearLayout llCoupon;
    @BindView(R.id.ll_nocoupon)
    LinearLayout llNocoupon;
    @BindView(R.id.rl_coupon)
    RelativeLayout rlcoupon;
    @BindView(R.id.relation_recycle)
    RecyclerView relationRecycle;
    @BindView(R.id.tv_recomm)
    TextView tvrecomm;
    @BindView(R.id.view_recomm)
    View view_recomm;
    @BindView(R.id.recomm_layout)
    ViewGroup recommLayout;
    @BindView(R.id.nocoupon_reserve_price)
    TextView nocoupon_reservePrice;
    @BindView(R.id.volume_nocoupon)
    TextView nocoupon_volume;
    @BindView(R.id.ll_price_volum)
    LinearLayout llPriceVolum;


    private String num_iid; //商品id
    private String coupon_click_url; //商品优惠券链接
    private int usertype;//天猫或淘宝
    private String coupon_info;//优惠券金额
    private List<String> smallImagesBean = new ArrayList<>();
    private boolean isCollect = true;
    private RelationListAdapter relationListAdapter;//相关推荐列表
    private List<RelationBean> mProductLists = new ArrayList<>();
    private ProductDetail mProductDetail;
    private AlibcShowParams alibcShowParams;//页面打开方式，默认，H5，Native
    private AlibcTaokeParams alibcTaokeParams = null;
    private Map<String, String> exParams;//yhhpass参数


    @Override
    protected int getLayoutId() {
        return R.layout.activity_goods_detail;
    }

    @Override
    protected GoodsDetailPresenter createPresenter() {
        return new GoodsDetailPresenter(mContext);
    }

    @Override
    protected void initView() {
        //取出数据
        Intent intent = getIntent();
        num_iid = intent.getStringExtra("num_iid");
        usertype = intent.getIntExtra("user_type", 0);
        coupon_click_url = intent.getStringExtra("Coupon_click_url");
        coupon_info = intent.getStringExtra("coupon_info");

        //百川数据初始化
        alibcShowParams = new AlibcShowParams(OpenType.Native, false);
        exParams = new HashMap<>();
        exParams.put("isv_code", "appisvcode");
        exParams.put("alibaba", "杭州圣利");//自定义参数部分，可任意增删改
        //淘客参数
        alibcTaokeParams = new AlibcTaokeParams();
        alibcTaokeParams.adzoneid = "82937300330";
        alibcTaokeParams.pid = "mm_197520002_297650476_82937300330";
        alibcTaokeParams.extraParams = new HashMap<>();
        alibcTaokeParams.extraParams.put("taokeAppkey", "25525885");

        //请求产品数据
        mPresenter.getProductDetail(num_iid);
        //商品是否被收藏
        mPresenter.checkCollect(num_iid);
        setLayout();
    }

    private void setLayout() {
        if (coupon_info != null && !TextUtils.isEmpty(coupon_info)) {
            //优惠券金额
            couponinfo.setText("￥" + coupon_info.substring(coupon_info.lastIndexOf("减") + 1, coupon_info.lastIndexOf("元")));
            //底部按钮显示可以用优惠券购买
            llNocoupon.setVisibility(View.GONE);
            llCoupon.setVisibility(View.VISIBLE);
        } else {
            //无优惠券时,将按钮隐藏
            rlcoupon.setVisibility(View.GONE);
            llNocoupon.setVisibility(View.VISIBLE);
            llCoupon.setVisibility(View.GONE);
            nocoupon_volume.setVisibility(View.VISIBLE);
            nocoupon_reservePrice.setVisibility(View.VISIBLE);
            llPriceVolum.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        mPresenter.getRelation(num_iid);
        //相关推荐列表
        relationListAdapter = new RelationListAdapter(mProductLists);
        relationRecycle.setLayoutManager(new GridLayoutManager(this, 2));
        relationRecycle.setAdapter(relationListAdapter);
        relationRecycle.addItemDecoration(new MarginDecoration(mContext));
        relationListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                intentSelf(relationListAdapter.getItem(position));

            }
        });
    }

    private void intentSelf(RelationBean item) {
        Intent intent = new Intent(this, GoodsDetailActivity.class);
        intent.putExtra("user_type", item.getUser_type());
        intent.putExtra("num_iid", item.getNum_iid());
        //intent.putExtra("Coupon_click_url",relationListAdapter.getItem(position).getCoupon_click_url());
        startActivity(intent);
    }

    @Override
    public void ShowProductDetail(final ProductDetail productDetails) {
        mProductDetail=productDetails;
        //商品banner
        if (productDetails.getSmall_images()!=null){
        smallImagesBean = productDetails.getSmall_images().getString();
        List<String> url = new ArrayList<>();
        mBanner.setData(smallImagesBean, url);
        mBanner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
            @Override
            public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                Glide.with(GoodsDetailActivity.this)
                        .load(smallImagesBean.get(position))
                        .apply(RequestOptions.placeholderOf(R.drawable.goodsdetail_bitmap))
                        .into(itemView);
            }
        });
        }
        //设置商品标题
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder("  " + productDetails.getTitle());
        DynamicDrawableSpan ab = new DynamicDrawableSpan() {
            @Override
            public Drawable getDrawable() {
                //if (productDetails.getUser_type())
                if (productDetails.getUser_type() == 0) {
                    Drawable drawable = getResources().getDrawable(R.drawable.taobao);
                    drawable.setBounds(0, 0, 75, 50);
                    return drawable;
                } else {
                    Drawable drawable = getResources().getDrawable(R.drawable.tianmao);
                    drawable.setBounds(0, 0, 75, 50);
                    return drawable;
                }
            }
        };
        stringBuilder.setSpan(ab, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mGoodsName.setText(stringBuilder);
        //商品价格
        zkFinalPrice.setText(productDetails.getZk_final_price());
        //淘宝价格
        reservePrice.setText("淘宝价格￥" + productDetails.getReserve_price());
        nocoupon_reservePrice.setText("淘宝价格￥" + productDetails.getReserve_price());
        //已付款人数
        volume.setText(productDetails.getVolume() + "人已付款");
        nocoupon_volume.setText(productDetails.getVolume() + "人已付款");
        //获取店铺信息
        mPresenter.getShop(productDetails.getNick());
        //领券购买价格
        if (coupon_info != null && !TextUtils.isEmpty(coupon_info)) {
            priceCoupon.setText("￥" + (Double.valueOf(productDetails.getZk_final_price()) - Double.valueOf(coupon_info.substring(coupon_info.lastIndexOf("减") + 1, coupon_info.lastIndexOf("元")))));
        }
        //直接购买价格
        priceBuy.setText("￥" + productDetails.getZk_final_price());
    }

    @Override
    public void ShowToast(String ssss) {
        if (isCollect) {
            ToastUtil.showShort(this, "已取消收藏" + ssss);
        } else {
            ToastUtil.showShort(this, "收藏成功" + ssss);
        }
    }

    @Override
    public void ShowCheckCollect(CheckCollect checkCollect) {
        if (checkCollect.getCode() == 1) {
            isCollect = false;
            collect.setImageResource(R.drawable.collect_star_select);
        } else {
            isCollect = true;
            collect.setImageResource(R.drawable.collect_star_normal);
        }
    }

    @Override
    public void ShowShop(ShopDetail shopDetail) {
        shopTitle.setText(shopDetail.getShop_title());
        sellerNick.setText(shopDetail.getSeller_nick());
        Glide.with(this).load(shopDetail.getPict_url()).apply(RequestOptions.placeholderOf(R.drawable.classify_bitmap)).into(shopIcon);
    }

    @Override
    public void ShowRelation(List<RelationBean> relationBean) {
        relationListAdapter.setNewData(relationBean);
    }

    @Override
    public void showNoData() {
        recommLayout.setVisibility(View.GONE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.iv_back, R.id.iv_share, R.id.shop_url, R.id.rl_collect, R.id.ll_price_buy, R.id.ll_price_coupon, R.id.ll_nocoupon})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
                //toActivity(ShareActivity.class);
                UMShareUtil.shareWeb(this,mProductDetail.getItem_url(),mProductDetail.getCat_leaf_name(),mProductDetail.getTitle(),mProductDetail.getPict_url(),R.drawable.thumb);
                break;
            case R.id.shop_url://店铺地址

                break;
            case R.id.rl_collect:
                if (ConfigUtil.isLogin()) {
                    if (isCollect) {
                        //收藏
                        mPresenter.getWriteCollect(num_iid, 1);
                        collect.setImageResource(R.drawable.collect_star_select);
                        isCollect = false;
                    } else {
                        //取消收藏
                        mPresenter.getWriteCollect(num_iid, 0);
                        collect.setImageResource(R.drawable.collect_star_normal);
                        isCollect = true;
                    }
                } else {
                    toActivity(LoginActivity.class);
                }
                break;
            //不用优惠券直接购买
            case R.id.ll_price_buy:
                mPresenter.couponCount(1);//统计
                AlibcDetailPage detailPage = new AlibcDetailPage(num_iid);
                AlibcTrade.show(this, detailPage, alibcShowParams, null, exParams, new AlibcTradeCallback() {
                    @Override
                    public void onTradeSuccess(AlibcTradeResult alibcTradeResult) {

                    }

                    @Override
                    public void onFailure(int i, String s) {

                    }
                });
                break;
            //用优惠券购买
            case R.id.ll_price_coupon:
                mPresenter.couponCount(2);//统计
                AlibcBasePage page = new AlibcPage(coupon_click_url);
                AlibcTrade.show(this, page, alibcShowParams, alibcTaokeParams, exParams, new AlibcTradeCallback() {
                    @Override
                    public void onTradeSuccess(AlibcTradeResult alibcTradeResult) {
                    }
                    @Override
                    public void onFailure(int i, String s) {
                    }
                });
                break;
            //无优惠券直接购买
            case R.id.ll_nocoupon:
                mPresenter.couponCount(1);//统计
                AlibcDetailPage detailPage1 = new AlibcDetailPage(num_iid);
                AlibcTrade.show(this, detailPage1, alibcShowParams, alibcTaokeParams, exParams, new AlibcTradeCallback() {
                    @Override
                    public void onTradeSuccess(AlibcTradeResult alibcTradeResult) { }
                    @Override
                    public void onFailure(int i, String s) { }
                });
                break;
        }
    }

    //recycleview item设置间距
    class MarginDecoration extends RecyclerView.ItemDecoration {
        private int margintop, marginleft, marginright;

        public MarginDecoration(Context context) {
            margintop = ScreenUtil.dp2px(context, 8);
            marginleft = ScreenUtil.dp2px(context, 16);
            marginright = ScreenUtil.dp2px(context, 4);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            if (parent.getChildLayoutPosition(view) % 2 == 0) {
                outRect.set(marginleft, 0, marginright, margintop);
            } else {
                outRect.set(marginright, 0, marginleft, margintop);
            }
        }
    }

    @Override
    protected void onDestroy() {
        //调用了AlibcTrade.show方法的Activity都需要调用AlibcTradeSDK.destory()
        AlibcTradeSDK.destory();
        super.onDestroy();
    }

}
